package com.aisino.ams;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

import java.io.IOException;

public class RemoteShellExecutor {
    private Connection connection;

    private String ipAddress;

    private String userName;

    private String password;

    private static final int TIME_OUT = 0;  //表示不超时

    /**
     * 构造函数
     * @param ipAddress  远程ipAddress
     * @param userName  远程机器用户名
     * @param password  远程机器密码
     */
    public RemoteShellExecutor(String ipAddress,String userName,String password){
        this.ipAddress = ipAddress;
        this.userName = userName;
        this.password = password;
    }

    /**
     * 登录
     * @return
     * @throws IOException
     */
    public boolean login() throws IOException{

        connection = new Connection(ipAddress);

        connection.connect();

        return connection.authenticateWithPassword(userName, password);
    }

    /**
     * 执行shell
     * @param shell
     * @return
     * @throws Exception
     */
    public int exec(String shell) throws Exception{

        int ret = -1;

        try {
            if(login()){
                Session session = connection.openSession();
                session.execCommand(shell);
                //session.execCommand("echo '12234' >> /home/qihao/test.txt");
                Thread.sleep(1000);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                Thread.sleep(1000);
                ret = session.getExitStatus();
            }else {
                throw new Exception("登录远程机器失败" + ipAddress); // 自定义异常类 实现略
            }
        }finally {
            if ( connection != null){
                connection.close();
            }
        }
        return ret;

    }


}
